package yxy.game.pm2.bean.db.newDao;

import yxy.apple.db.DbManager;
import yxy.game.pm2.bean.db.po.MailPo;

import java.util.ArrayList;
import java.util.List;

public class MailDAO {

    private static final String
            REPLACE_ONE = "replace into `mail` (`pCode`, `code`, `type`, `title`, `content`, `rewards`, `reason`, `readed`, `rewarded`, `sendTime`, `expiryTime`, `updateTime`)" +
            " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            SELECT_ALL = "select * from `mail` where pCode = ? and expiryTime > now()",
            DELETE = "delete from `mail` where pCode = ? and `updateTime` != ?";

    public static boolean replace(String pCode, List<MailPo> mailPos, long updateTime) {
        List<Object[]> list = new ArrayList<>();
        for (MailPo mailPo : mailPos) {
            Object[] objects = new Object[]{pCode, mailPo.getCode(), mailPo.getType(), mailPo.getTitle(), mailPo.getContent(),mailPo.getRewards(), mailPo.getReason(),
                    mailPo.isReaded(), mailPo.isRewarded(), mailPo.getSendTime(), mailPo.getExpiryTime(),updateTime};
            list.add(objects);
        }
        int[] ints = DbManager.instance().executeBatchCommand(REPLACE_ONE, list);
        return ints.length == mailPos.size();
    }

    public static List<MailPo> getList(String pCode) {
        return DbManager.instance().executeQueryObjectList(SELECT_ALL, new Object[]{pCode}, MailPo.builder);
    }

    public static void delete(String pCode, long updateTime) {
        DbManager.instance().executeCommand(DELETE, new Object[]{pCode, updateTime});
    }

    public static void deleteByCode(String pCode, String code) {
        String sql = "delete from `mail` where pCode = ? and `code` = ?";
        DbManager.instance().executeCommand(sql, new Object[]{pCode, code});
    }

}
